import csv
import lineup_r1
import string
from equivalence import equivalence
from optparse import OptionParser

def csv_reader(input_file, lineup_obj):
  with open(input_file) as fm:
    fm_bsv = csv.reader(fm, delimiter='|', quotechar=None)
    for row in fm_bsv:
      #if isinstance(row[6].strip(), int):
      if row[6].strip() !="":
        headend_id, device_type_code, lcn, onid, tsid, sid, frequency, ch_id, ch_name = \
            row[0].strip(), row[1].strip(), row[2].strip(), row[3].strip(), row[4].strip(), row[5].strip(), int(row[6].strip()), row[7].strip(), row[8].strip()
      else:
        headend_id, device_type_code, lcn, onid, tsid, sid, frequency, ch_id, ch_name = \
            row[0].strip(), row[1].strip(), row[2].strip(), row[3].strip(), row[4].strip(), row[5].strip(), row[6].strip(), row[7].strip(), row[8].strip()

      lineup_obj.append(lineup_r1.Lineup(headend_id,device_type_code,lcn,onid,tsid,sid,frequency,ch_id,ch_name))

def add_find_index(list):
  y=[]
  for le in list:
    y.append([le, 0])
  return y

def main():
  metadata=[]
  metadata_with_index=[]
  fielddata=[]
  fielddata_with_index=[]

  parser = OptionParser()
  parser.add_option("-m", "--meta", dest="meta_filename", \
      help="metadata input file", metavar="FILE")
  parser.add_option("-f", "--field", dest="field_filename", \
      help="fielddata input file", metavar="FILE")
  parser.add_option("-e", "--equiv", dest="equiv_filename", \
      help="equivalence channels input file", metavar="FILE")
  parser.add_option("-o", "--outputdir", dest="outputdir", \
      help="output dir", metavar="DIR")
  (options, args) = parser.parse_args()

  csv_reader(options.meta_filename, metadata)
  metadata_with_index=add_find_index(metadata)
  csv_reader(options.field_filename, fielddata)
  fielddata_with_index=add_find_index(fielddata)

  eq = equivalence()
  with open(options.equiv_filename) as fm:
    fm_bsv = csv.reader(fm, delimiter='|', quotechar=None)
    for row in fm_bsv:
      eq.merge(row[0], row[1])

  i = 0
  while i < len(fielddata_with_index):
    j = 0
    while j < len(metadata_with_index):
      if fielddata_with_index[i][0].eq_without_ch_name(metadata_with_index[j][0]):
        if eq.are_equivalent(fielddata_with_index[i][0]._ch_name, metadata_with_index[j][0]._ch_name): 
          fielddata_with_index[i][1] = j+1
          metadata_with_index[j][1] = i+1
        else: 
          fielddata_with_index[i][1] = -(j+1)
          metadata_with_index[j][1] = -(i+1)
        break
      j = j + 1
    i = i + 1
  
  field_only_file = open(options.outputdir + "/report-field_only.txt", 'a')
  matched_file = open(options.outputdir + "/report-matched.txt", 'a')
  metadata_only_file = open(options.outputdir + "/report-metadata_only.txt", 'a')
  only_ch_name_mismatch_file = open(options.outputdir + "/report-only_ch_name_mismatched.txt", 'a')

  
  #print("----- Field Only -----")
  for field, f_index in fielddata_with_index:
    if f_index == 0:
      field_only_file.write(field.__str__()+"\n")

  #print("----- Metadata Only -----")
  for meta, m_index in metadata_with_index:
    if m_index == 0:
      metadata_only_file.write(meta.__str__()+"\n")
      #print(meta)

  #print("----- Matched -----")
  for field, f_index in fielddata_with_index:
    if f_index > 0:
      matched_file.write(field.__str__()+"\n")
      matched_file.write(metadata_with_index[f_index-1][0].__str__()+"\n")
      matched_file.write("--------"+"\n")
      #print(field)
      #print(metadata_with_index[f_index-1][0]) 
      #print("--------")

  #print("----- Only Channel name mismatched -----")
  for field, f_index in fielddata_with_index:
    if f_index < 0:
      only_ch_name_mismatch_file.write(field.__str__()+"\n")
      only_ch_name_mismatch_file.write(metadata_with_index[-(f_index)-1][0].__str__()+"\n")
      only_ch_name_mismatch_file.write("{0}|{1}".format(field._ch_name, metadata_with_index[-(f_index)-1][0]._ch_name)+"\n")
      only_ch_name_mismatch_file.write("--------"+"\n")
      #print(field)
      #print(metadata_with_index[-(f_index)-1][0])
      #print("{0}|{1}".format(field._ch_name, metadata_with_index[-(f_index)-1][0]._ch_name))
      #print("--------")

  field_only_file.close()
  matched_file.close()
  metadata_only_file.close()
  only_ch_name_mismatch_file.close()

if __name__ == "__main__":
  main()
